<?php

class _F_EXTENSION_DATA_CONNECTION_ extends _F_EXTENSION_ {
	
	public $pdo;
	public $dsn;
	public $username;
	public $password;
	public $driver_options = array();
	public $class;
	
	public $_f_name_quote_left_ = null;
	public $_f_name_quote_right_;
	
	public function __construct($name,$options) {
		$this->put_properties($options);
		f()->register_method($name,array($this,'data_connection'));
	}
	
	public function data_connection() {
		return $this;
	}

	public function begin() {
		$this->connection->beginTransaction();
	}

	public function commit() {
		$this->connection->commit();
	}

	public function roll_back() {
		$this->connection->rollBack();
	}
	
	public function select($from = null, $select = '*',$params = array(),$class = null) {
		return new _F_EXTENSION_DATA_SELECT_($this,
			array('from' => $from, 'select' => $select),
			$params,$class);
	}

	public function query($query) {
		return new _F_EXTENSION_DATA_QUERY_($this,$query);
	}

	public function _f_get_connection_() {
		if ($this->pdo === null) {
			$this->pdo = new PDO($this->dsn,$this->username,
				$this->password,$this->driver_options);
			if ($this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql')
				$this->pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,1); 
			// TODO: check the connection and report error
		}
		return $this->pdo;
	}

	public function create($table,$class) {
		$obj = new $class;
		$obj->_f_db_ = $this;
		return $obj;
	}
		
	public function find_by_pkey($table,$class,$pkey) {
		$obj = new $class;
		$results = $this->select($this->quote_name($table),
			'*',array(':_f_pkey_' => $pkey),$class)
			->where($obj->_f_pkey_field_.' = :_f_pkey_')
			->exec();
		foreach ($results as $obj) {
			$obj->_f_db_ = $this;
			$pkfield = $obj->_f_pkey_field_;
			$obj->_f_pkey_ = $obj->$pkfield;
			return $obj;
		}
		return null;
	}
	
	public function find_all($table,$class) {		
		return $this->select($this->quote_name($table),
			'*',array(),$class)->exec();
	}
	
	public function quote_name($name) {
		if ($this->_f_name_quote_left_ === null) {
			switch ($this->connection->getAttribute(PDO::ATTR_DRIVER_NAME)) {
				case 'mysql': 
					$this->_f_name_quote_left_ = '`'; 
					$this->_f_name_quote_right_ = '`'; 
					break;
				case 'sqlsrv': 
					$this->_f_name_quote_left_ = '['; 
					$this->_f_name_quote_right_ = ']'; 
					break;
				default: 
					$this->_f_name_quote_left_ = '"'; 
					$this->_f_name_quote_right_ = '"'; 
			}
		}
		return $this->_f_name_quote_left_.$name.$this->_f_name_quote_right_;
	}

}
